<template>
    <div class="memory-game">
        <div class="game-header">
            <h2>记忆大师</h2>
            <div class="game-info">
                <div class="stats">
                    <span>步数: {{ moves }}</span>
                    <span>配对: {{ matches }}/{{ totalPairs }}</span>
                    <span>时间: {{ formatTime(timer) }}</span>
                </div>
                <div class="level-select">
                    <span>难度:</span>
                    <el-select v-model="difficulty" @change="startNewGame" :disabled="gameStarted">
                        <el-option label="简单 (4x4)" value="easy" />
                        <el-option label="中等 (6x6)" value="medium" />
                        <el-option label="困难 (8x8)" value="hard" />
                    </el-select>
                </div>
            </div>
            <div class="controls">
                <el-button type="primary" @click="startNewGame">新游戏</el-button>
                <el-button type="warning" @click="showHint" :disabled="!canShowHint">提示 ({{ hintCount }})</el-button>
            </div>
        </div>

        <div class="game-board" :class="difficulty">
            <div v-for="(card, index) in cards" 
                 :key="index" 
                 class="card"
                 :class="{ 
                     'flipped': card.isFlipped,
                     'matched': card.isMatched,
                     'hint': card.isHint
                 }"
                 @click="flipCard(index)">
                <div class="card-inner">
                    <div class="card-front">
                        <el-icon><QuestionFilled /></el-icon>
                    </div>
                    <div class="card-back">
                        <el-icon v-if="card.icon"><component :is="card.icon" /></el-icon>
                        <span v-else>{{ card.value }}</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 胜利弹窗 -->
        <el-dialog
            v-model="showVictoryDialog"
            title="恭喜!"
            width="300px"
            :show-close="false"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <div class="victory-content">
                <p>你完成了游戏！</p>
                <p>用时: {{ formatTime(timer) }}</p>
                <p>步数: {{ moves }}</p>
                <p>得分: {{ calculateScore() }}</p>
            </div>
            <template #footer>
                <el-button type="primary" @click="startNewGame">再来一局</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import * as Icons from '@element-plus/icons-vue';

// 游戏配置
const difficulty = ref('easy');
const difficultyConfig = {
    easy: { rows: 4, cols: 4, hintCount: 3 },
    medium: { rows: 6, cols: 6, hintCount: 4 },
    hard: { rows: 8, cols: 8, hintCount: 5 }
};

// 游戏状态
const cards = ref<Array<{
    value: string | number;
    icon?: string;
    isFlipped: boolean;
    isMatched: boolean;
    isHint: boolean;
}>>([]);
const moves = ref(0);
const matches = ref(0);
const timer = ref(0);
const gameStarted = ref(false);
const showVictoryDialog = ref(false);
const hintCount = ref(3);
const timerInterval = ref<number | null>(null);
const canFlip = ref(true);

// 计算属性
const totalPairs = computed(() => {
    const config = difficultyConfig[difficulty.value as keyof typeof difficultyConfig];
    return (config.rows * config.cols) / 2;
});

const canShowHint = computed(() => {
    return gameStarted.value && hintCount.value > 0;
});

// 图标列表
const iconList = Object.keys(Icons).filter(key => key !== 'default');

// 生成卡片
const generateCards = () => {
    const config = difficultyConfig[difficulty.value as keyof typeof difficultyConfig];
    const totalCards = config.rows * config.cols;
    const pairs = totalCards / 2;
    
    // 创建配对的卡片
    const values: Array<{ value: string | number; icon?: string }> = [];
    
    // 使用图标和数字的混合
    for (let i = 0; i < pairs; i++) {
        if (i < iconList.length && Math.random() > 0.5) {
            values.push({ value: i.toString(), icon: iconList[i] });
            values.push({ value: i.toString(), icon: iconList[i] });
        } else {
            values.push({ value: i.toString() });
            values.push({ value: i.toString() });
        }
    }

    // 随机打乱
    for (let i = values.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [values[i], values[j]] = [values[j], values[i]];
    }

    // 创建卡片对象
    cards.value = values.map(v => ({
        ...v,
        isFlipped: false,
        isMatched: false,
        isHint: false
    }));
};

// 开始新游戏
const startNewGame = () => {
    // 重置游戏状态
    moves.value = 0;
    matches.value = 0;
    timer.value = 0;
    gameStarted.value = true;
    showVictoryDialog.value = false;
    canFlip.value = true;
    
    // 重置提示次数
    const config = difficultyConfig[difficulty.value as keyof typeof difficultyConfig];
    hintCount.value = config.hintCount;

    // 生成新卡片
    generateCards();

    // 启动计时器
    if (timerInterval.value) {
        clearInterval(timerInterval.value);
    }
    timerInterval.value = setInterval(() => {
        timer.value++;
    }, 1000);
};

// 翻牌逻辑
const flipCard = (index: number) => {
    if (!canFlip.value || !gameStarted.value) return;
    if (cards.value[index].isMatched || cards.value[index].isFlipped) return;

    const flippedCards = cards.value.filter(card => card.isFlipped && !card.isMatched);
    if (flippedCards.length >= 2) return;

    // 翻开卡片
    cards.value[index].isFlipped = true;
    
    // 检查配对
    const flipped = cards.value.filter(card => card.isFlipped && !card.isMatched);
    if (flipped.length === 2) {
        moves.value++;
        canFlip.value = false;

        // 检查是否匹配
        if (flipped[0].value === flipped[1].value) {
            // 匹配成功
            setTimeout(() => {
                flipped.forEach(card => card.isMatched = true);
                matches.value++;
                canFlip.value = true;
                
                // 检查游戏是否结束
                if (matches.value === totalPairs.value) {
                    gameVictory();
                }
            }, 500);
        } else {
            // 匹配失败
            setTimeout(() => {
                flipped.forEach(card => card.isFlipped = false);
                canFlip.value = true;
            }, 1000);
        }
    }
};

// 显示提示
const showHint = () => {
    if (hintCount.value <= 0) return;

    // 找到未匹配的卡片对
    const unmatched = cards.value.filter(card => !card.isMatched && !card.isFlipped);
    if (unmatched.length === 0) return;

    // 随机选择一对卡片
    const firstCard = unmatched[Math.floor(Math.random() * unmatched.length)];
    const matchingCard = unmatched.find(card => 
        card !== firstCard && card.value === firstCard.value
    );

    if (matchingCard) {
        // 显示提示效果
        firstCard.isHint = true;
        matchingCard.isHint = true;
        hintCount.value--;

        setTimeout(() => {
            firstCard.isHint = false;
            matchingCard.isHint = false;
        }, 1000);
    }
};

// 游戏胜利
const gameVictory = () => {
    if (timerInterval.value) {
        clearInterval(timerInterval.value);
    }
    gameStarted.value = false;
    showVictoryDialog.value = true;
};

// 计算得分
const calculateScore = () => {
    const baseScore = 1000;
    const timeDeduction = Math.floor(timer.value / 2);
    const movesDeduction = moves.value * 10;
    return Math.max(0, baseScore - timeDeduction - movesDeduction);
};

// 格式化时间
const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
};

// 生命周期钩子
onMounted(() => {
    startNewGame();
});

onUnmounted(() => {
    if (timerInterval.value) {
        clearInterval(timerInterval.value);
    }
});
</script>

<style scoped>
.memory-game {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.game-header {
    text-align: center;
    margin-bottom: 20px;
}

.game-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 15px 0;
}

.stats {
    display: flex;
    gap: 20px;
}

.controls {
    margin: 15px 0;
}

.game-board {
    display: grid;
    gap: 10px;
    margin: 0 auto;
    perspective: 1000px;
}

.game-board.easy {
    grid-template-columns: repeat(4, 1fr);
    max-width: 400px;
}

.game-board.medium {
    grid-template-columns: repeat(6, 1fr);
    max-width: 600px;
}

.game-board.hard {
    grid-template-columns: repeat(8, 1fr);
    max-width: 800px;
}

.card {
    aspect-ratio: 1;
    cursor: pointer;
    position: relative;
    transform-style: preserve-3d;
    transition: transform 0.5s;
}

.card.flipped {
    transform: rotateY(180deg);
}

.card.matched {
    cursor: default;
}

.card.hint {
    animation: hint-animation 1s infinite;
}

.card-inner {
    position: relative;
    width: 100%;
    height: 100%;
    text-align: center;
    transform-style: preserve-3d;
}

.card-front,
.card-back {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.card-front {
    background-color: #409EFF;
    color: white;
}

.card-back {
    background-color: white;
    transform: rotateY(180deg);
    border: 2px solid #409EFF;
}

.matched .card-back {
    background-color: #67C23A;
    color: white;
}

.victory-content {
    text-align: center;
}

@keyframes hint-animation {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

@media (max-width: 768px) {
    .game-board.medium {
        max-width: 400px;
    }
    
    .game-board.hard {
        max-width: 500px;
    }
    
    .card-front,
    .card-back {
        font-size: 18px;
    }
}
</style>